package com.aicheyoudao.utils;

import java.io.IOException;
import java.net.UnknownHostException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.concurrent.TimeoutException;

import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.conn.ConnectTimeoutException;
import org.apache.http.conn.params.ConnManagerParams;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.params.BasicHttpParams;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.params.HttpParams;
import org.apache.http.util.EntityUtils;

import android.util.Log;

/**
 * @author Frank The basic http request methods
 * 
 */
public class HttpUtils {

	private final static int TIMEOUT = 10000;
	private static HttpClient defaultClient;
	public final static String HTTP_KEY_STATUS = "status";
	public final static String HTTP_KEY_CONTENT = "content";

	public static HashMap<String, Object> httpPost(String uri,
			NameValuePair args) throws ClientProtocolException, IOException,
			UnknownHostException, TimeoutException, ConnectTimeoutException {
		HashMap<String, Object> resContent = new HashMap<String, Object>();
		HttpPost httpPost = new HttpPost(uri);
		ArrayList<NameValuePair> arg = new ArrayList<NameValuePair>();
		arg.add(args);
		Log.i("info", args.getName() + "===" + args.getValue());
		httpPost.setEntity(new UrlEncodedFormEntity(arg, "UTF-8"));
		HttpResponse response = getDefaultHttpClient().execute(httpPost);
		int code = response.getStatusLine().getStatusCode();
		String httpEntity = "";
		if (HttpStatus.SC_OK == code) {
			httpEntity = EntityUtils.toString(response.getEntity());
			Log.i("info", "res=" + httpEntity);
		}
		resContent.put(HTTP_KEY_STATUS, code);
		resContent.put(HTTP_KEY_CONTENT, httpEntity);
		return resContent;
	}

	private static HttpClient getDefaultHttpClient() {
		HttpParams httpParams = new BasicHttpParams();
		ConnManagerParams.setTimeout(httpParams, TIMEOUT);
		HttpConnectionParams.setConnectionTimeout(httpParams, TIMEOUT);
		HttpConnectionParams.setSocketBufferSize(httpParams, TIMEOUT);
		defaultClient = new DefaultHttpClient(httpParams);
		return defaultClient;
	}

	public static void releaseHttp() {
		if (defaultClient != null)
			defaultClient.getConnectionManager().shutdown();
	}
}
